﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Medhurst.Unity.Configuration;
using System.Configuration;
using Medhurst.Unity.Examples;
using Medhurst.Unity.Examples.Plugins;

namespace Medhurst.Unity.ExampleHost
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a unity container
            var unity = new UnityContainer();

            // load configuration from yaml
            try
            {
                unity.LoadConfigurationFromYaml();
            }
            catch (ConfigurationErrorsException ex)
            {
                Console.Error.WriteLine("There is a problem with your configuration file: {0}", ex.Message);
                Environment.Exit(1); // return error code 1
                return;
            }

            // now use unity as you usually would
            // - plugins
            var plugins = unity.ResolveAll<IPlugin>();
            plugins.AsParallel().ForAll(p => p.Start());
            // - settings
            var settings = unity.Resolve<ISettings>();
            // - log
            var log = unity.Resolve<ILog>();
            log.Info("Logging is now active, using implementation: " + log.GetType().FullName);

            // show all unity resolved classes to prove configuration works
            Console.Out.WriteLine("Logging: {0}", log.GetType().FullName);
            Console.Out.WriteLine("Settings: {0}", settings.GetType().FullName);
            foreach (var plugin in plugins)
            {
                Console.Out.WriteLine("Plugin: {0}", plugin.GetType().FullName);
                if (plugin is Plugin2)
                {
                    var plugin2 = (Plugin2)plugin;
                    Console.Out.WriteLine(" - StringProperty={0}", plugin2.StringProperty);
                    Console.Out.WriteLine(" - NumericProperty={0}", plugin2.NumericProperty);
                    Console.Out.WriteLine(" - FloatProperty={0}", plugin2.FloatProperty);
                    if (plugin2.NameValueProperty != null)
                    foreach (string key in plugin2.NameValueProperty.Keys)
                        Console.Out.WriteLine(" - NameValueProperty.{0}={1}", key, plugin2.NameValueProperty[key]);
                }
            }

            // program blocking call
            Console.Error.WriteLine("Program is now running, press return to exit...");
            Console.ReadLine();

            // shutdown plug-ins
            plugins.AsParallel().ForAll(p => p.Stop());
        }
    }
}
